/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.uoc.tdp.pac4.only5.tools;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 *
 * @author Gerard
 */
public class DateTool {

    private static DateTool instance;
    private static SimpleDateFormat sdf;
    private static SimpleDateFormat sdf2;

    private DateTool() {
        sdf = new SimpleDateFormat("dd/MM/yyyy");
        sdf2 = new SimpleDateFormat("dd/MM/yyyy HH:mm");
    }

    public static DateTool getInstance() {
        return instance == null ? instance = new DateTool() : instance;
    }

    public String convertDateToString(Date date) {
        String result = null;
        if (date != null) {
            result = sdf.format(date);
        }
        return result;
    }

    public Date convertDateToString(String sDate) throws ParseException {
        Date date = null;
        if (StringTool.getInstance().isNotEmpty(sDate)) {
            date = sdf.parse(sDate);
        }
        return date;
    }
    
    public Date incrementDate(Date startDate, int hours){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        int hour = calendar.get(Calendar.HOUR_OF_DAY) + hours;
        if(hour > 24){
            calendar.set(Calendar.HOUR_OF_DAY, hour - 24);
            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)+1);
        } else {
            calendar.set(Calendar.HOUR_OF_DAY, hour);
        }
        return calendar.getTime();
    }
    
    public Date convertStringToDateWithHourAndMinutes(String sDate) throws ParseException {
        Date date = null;
        if (StringTool.getInstance().isNotEmpty(sDate)) {
            date = sdf2.parse(sDate);
        }
        return date;
    }
    
    public String convertDateToStringWithHourAndMinutes(Date date) throws ParseException {
        String sDate = null;
        if (date != null) {
            sDate = sdf2.format(date);
        }
        return sDate;
    }
    
    public Long getTimeBetweenToDates(Date start, Date end){
        Long difference = end.getTime() - start.getTime();
        difference = difference / (60*60*1000);
        return difference;
    }
    
    public java.sql.Date getSqlDate(Date date){
        java.sql.Date result = null;
        if(date != null){
            result = new java.sql.Date(date.getTime());
        }
        return result;
    }
    
    public boolean isEqualOrAfterToday(Date date){
        boolean result = false;
        if(date != null){
            Date today = new Date();
            if(today.getTime() >= date.getTime()){
                result = true;
            }    
        }
        return result;
    }
    
}
